//
//  FHTextView.swift
//  WeiBo
//
//  Created by qfh on 16/7/18.
//  Copyright © 2016年 qiufuhe. All rights reserved.
//

import UIKit
@IBDesignable
class FHTextView: UITextView {

    /// 懒加载控件
    private lazy var placeHolderLabel: UILabel = {
    
        let label = UILabel()
        
        label.font = UIFont.systemFontOfSize(12)

        label.text = "听说下雨天音乐和辣条更配哦~~~"
        
        label.textColor = UIColor.grayColor()
        
        label.numberOfLines = 0
 
        return label
    }()
    
    /// 占位符
    @IBInspectable var placeHolder: String? {
    
        didSet {
        
            placeHolderLabel.text = placeHolder
            
            
        }
    }
    /// 重写font
    override var font: UIFont? {
    
        didSet {

            if font == nil {
            
                return
            }
            
            placeHolderLabel.font = font
        }

        
    
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setUpUi()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /**
     设置ui
     */
    private func setUpUi() {
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        
        addSubview(placeHolderLabel)
        
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 5))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 8))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
        
        
        
    
    }
    
    /**
     text 有数据变化执行这个方法
     */
    @objc private func textChange() {
    
        
        placeHolderLabel.hidden = self.hasText()
    
    }
    
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }

}
